package com.anysoft.utils.login;

import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 网络工具,含cookie
 * 
 */
public class PictureCodeNetUtil {

	private static final String TAG = "PictureCodeNetUtil";
	public static String sessionid;

	/**
	 * 通过给定的URL地址返回一个输入流
	 * 
	 * @param urlPath
	 *            URL地址
	 * @return 通过给定的URL地址返回一个InputStream
	 */
	public static String getJsonByUrl(String urlPath, String body) {
		InputStream in = getLoginInputStreamByUrl(urlPath, body);
		if (in == null) {
			return null;
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int len = -1;
		try {
			while ((len = in.read(buf)) != -1) {
				baos.write(buf, 0, len);
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String json = null;
		try {
			json = new String(baos.toByteArray(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return json;
	}

	/**
	 * @param urlPath
	 * @return
	 */
	public static InputStream getLoginInputStreamByUrl(String urlPath,
			String body) {
		if (urlPath == null) {
			return null;
		}
		URL url = null;
		try {
			url = new URL(urlPath);
		} catch (MalformedURLException e3) {
			e3.printStackTrace();
			return null;
		}
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("cookie", SessionUtil.SessionID);
		} catch (IOException e2) {
			e2.printStackTrace();
			return null;
		}
		conn.setConnectTimeout(5000);
		try {
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded"); // 这两项是必须设置的
			Logger.i(TAG, "body = " + body);
			conn.setRequestProperty("Content-Length", body.getBytes().length
					+ "");
			conn.setDoOutput(true);
			conn.getOutputStream().write(body.getBytes()); // 写出消息体
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		int responseCode = -1;
		try {
			responseCode = conn.getResponseCode();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		if (responseCode != 200) {
			return null;
		}
		InputStream in = null;
		try {
			in = conn.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		return in;
	}

	/**
	 * 获取一个输入流
	 * 
	 * @param urlPath
	 * @param params
	 * @return
	 */
	public static InputStream getInputStreamByUrl(String urlPath,
			Map<String, String> params) {
		if (urlPath == null) {
			return null;
		}
		URL url = null;
		try {
			url = new URL(urlPath);
		} catch (MalformedURLException e3) {
			e3.printStackTrace();
			return null;
		}
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("cookie", SessionUtil.getSessionId(urlPath));
		} catch (IOException e2) {
			e2.printStackTrace();
			return null;
		}
		conn.setConnectTimeout(5000);
		try {
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded"); // 这两项是必须设置的
			String body = getBody(params);
			Logger.i(TAG, "body = " + body);
			conn.setRequestProperty("Content-Length", body.getBytes().length
					+ "");
			conn.setDoOutput(true);
			conn.getOutputStream().write(body.getBytes()); // 写出消息体
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		int responseCode = -1;
		try {
			responseCode = conn.getResponseCode();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		if (responseCode != 200) {
			return null;
		}
		InputStream in = null;
		try {
			in = conn.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

		return in;
	}

	private static String getBody(Map<String, String> params) {
		StringBuilder sb = new StringBuilder();
		Set<String> keySet = params.keySet();
		Iterator<String> it = keySet.iterator();
		boolean isFirst = true;
		while (it.hasNext()) {
			String key = it.next();
			String value = params.get(key);
			if (!isFirst) {
				sb.append("&");
			}
			// if (Constants.IS_LOCAL) {
			sb.append(key).append("=").append(value);
			// } else {
			// sb.append(key).append("=").append(URLEncoder.encode(value));
			// }
			isFirst = false;
		}
		return sb.toString();
	}

}
